<template>
  <div class="container">
    <div class="account-list">
      <van-list>
        <van-cell v-for="item in list" :key="item" :title="item.address" @click="setNow(item)" />
      </van-list>
    </div>

    <div class="operations">
      <!-- 转账部分 -->
      <div class="transfer-section">
        <h3>转账操作</h3>
        <van-field v-model="tranIcon.address" label="接收地址" placeholder="请输入地址" />
        <van-field v-model="tranIcon.balance" label="金额" placeholder="请输入金额" type="number" />
        <div>当前地址：{{ nowInfo.address }}</div>
        <div>当前钱包余额：{{ nowInfo.balance }} MTH</div>
        <div class="button-group">
          <van-button @click="giveMoney">转账 MTK</van-button>
          <van-button @click="approveToken">授权 MTK</van-button>
          <van-button @click="multiTransferToken">批量转 MTK</van-button>
          <van-button @click="multiTransferEth">批量转 ETH</van-button>
          <van-button @click="transEth">转 ETH</van-button>
        </div>
      </div>

      <!-- 投票部分 -->
      <div class="voting-section">
        <h3>投票系统</h3>
        <div v-if="nowInfo.votingStatus" class="remaining-time">
          剩余时间: {{ formatTime(nowInfo.remainingTime) }}
        </div>

        <div class="candidates-list">
          <div v-for="(candidate, index) in nowInfo.candidates" :key="index" class="candidate-item">
            <span>{{ candidate.name }}: {{ candidate.voteCount }}票</span>
            <van-button :disabled="nowInfo.hasVoted || !nowInfo.votingStatus" @click="vote(index)">
              投票
            </van-button>
          </div>
        </div>

        <!-- 添加候选人（仅管理员可见） -->
        <div v-if="nowInfo.isOwner" class="add-candidate">
          <van-field v-model="newCandidateName" placeholder="输入候选人名称" />
          <van-button @click="addCandidate(newCandidateName)">添加候选人</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useWeb3 } from '../composables/useWeb3';
import { useContract } from '../composables/useContract';
import { handleWeb3Error } from '../utils/error';
import { tokenAbi, airdropAbi, sendEthAbi, votingAbi } from '../contracts/abi';
import { CONTRACT_ADDRESSES } from '../contracts/config';

// 状态管理
const { provider, signer, account, isConnected, connect } = useWeb3();

// 合约实例
const tokenContract = useContract(CONTRACT_ADDRESSES.SEPOLIA.TOKEN, tokenAbi);
const airdropContract = useContract(CONTRACT_ADDRESSES.SEPOLIA.AIRDROP, airdropAbi);
const votingContract = useContract(CONTRACT_ADDRESSES.SEPOLIA.VOTING, votingAbi);

const list = ref([]);
const nowInfo = reactive({
  address: '',
  balance: '',
  isOwner: false,
  votingStatus: false,
  remainingTime: 0,
  candidates: [],
  hasVoted: false
});

const tranIcon = reactive({
  address: '',
  balance: ''
});

const newCandidateName = ref('');

const votingStatus = ref(false);
const tokenBalance = ref('0');
const loading = ref(false);

// 初始化
async function init() {
  try {
    if (!isConnected.value) {
      await connect();
    }

    if (isConnected.value) {
      airdropContract.init();
      votingContract.init();
      tokenContract.init();
      
      await updateVotingStatus();
      await updateTokenBalance();
    }
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 更新投票状态
async function updateVotingStatus() {
  try {
    votingStatus.value = await votingContract.read('hasVoted', account.value);
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 更新代币余额
async function updateTokenBalance() {
  try {
    const balance = await tokenContract.read('balanceOf', account.value);
    tokenBalance.value = balance.toString();
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 更新余额
async function updateBalances() {
  try {
    if (!account.value) return;
    const balance = await tokenContract.read('balanceOf', account.value);
    nowInfo.balance = ethers.formatEther(balance);
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 设置当前账户
async function setNow(item) {
  try {
    nowInfo.address = item.address;
    await updateBalances();
    await updateVotingStatus();

    // 检查是否是合约拥有者
    const owner = await votingContract.read('owner');
    nowInfo.isOwner = owner.toLowerCase() === item.address.toLowerCase();
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 转账 MTK
async function giveMoney() {
  try {
    if (!tranIcon.address || !tranIcon.balance) {
      throw new Error('请输入地址和金额');
    }
    
    const amount = ethers.parseEther(tranIcon.balance);
    await tokenContract.write('transfer', tranIcon.address, amount);
    await updateBalances();
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 投票
async function vote(candidateIndex) {
  try {
    await votingContract.write('vote', candidateIndex);
    await updateVotingStatus();
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 添加候选人
async function addCandidate(name) {
  try {
    if (!name) throw new Error('请输入候选人名称');
    await votingContract.write('addCandidate', name);
    await updateVotingStatus();
  } catch (error) {
    handleWeb3Error(error);
  }
}

// 格式化时间
function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
}

onMounted(() => {
  init();
});
</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.account-list {
  flex: 1;
  max-width: 400px;
}

.operations {
  flex: 2;
}

.transfer-section,
.voting-section {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.candidates-list {
  margin-top: 20px;
}

.candidate-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.add-candidate {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.remaining-time {
  color: #666;
  margin-bottom: 10px;
}
</style>
